<template>
  <div class="news-dict-container">
    <!-- 查询区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">

        <el-form-item label="字典类型">
          <el-select
              v-model="searchForm.dictType"
              placeholder="请选择字典类型"
              clearable
              style="width: 150px"
          >
            <el-option v-for="type in dictTypes" :label="type" :value="type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字典名称">
          <el-input v-model="searchForm.dictName" placeholder="请输入字典名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>


<!--    字典列表-->
    <el-card>
      <div slot="header" class="clearfix">
        <span>字典列表</span>
        <el-button
            style="float: right; margin-top: -5px"
            type="primary"
            @click="handleAdd"
        >
          <i class="el-icon-plus"></i> 新增
        </el-button>
      </div>
      <!-- 数据列表区域 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="dictId" label="ID" width="120"></el-table-column>
        <el-table-column prop="dictType" label="字典类型"></el-table-column>
        <el-table-column prop="dictCode" label="字典编码"></el-table-column>
        <el-table-column prop="dictName" label="字典名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="sortOrder" label="排序"></el-table-column>
        <el-table-column prop="status" label="是否启用">
          <template #default="{ row }">
            <el-tooltip :content="row.isActive === 1 ? '正常' : '禁用'" placement="top">
              <el-switch
                  v-model="row.isActive"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                  @change="newStatus => handleSwitchChange(row, newStatus)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
        >
          <template #default="{ row }">
            <el-link type="danger" @click="handleDelete(row)">删除</el-link>
            <el-divider direction="vertical" />
            <el-link type="success" @click="handleEdit(row)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>



    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 12, 20, 30]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right"
    ></el-pagination>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        title="字典信息"
        v-model="dialogVisible"
        width="50%"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" placeholder="请输入字典类型"></el-input>
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input v-model="form.dictCode" placeholder="请输入字典编码"></el-input>
        </el-form-item>
        <el-form-item label="字典名称">
          <el-input v-model="form.dictName" placeholder="请输入字典名称"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              type="textarea"
              v-model="form.description"
              placeholder="请输入描述信息"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sortOrder" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
              v-model="form.isActive"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';
export default {
  name: 'NewsDict',
  data() {
    return {
      // 查询表单
      searchForm: {
        dictType: '',
        dictName: ''
      },
      dictTypes: [],
      // 表格数据
      tableData: [],
      // 分页总条数
      total: 0,
      current:1,
      size:6,
      // 选中项
      selectedRows: [],
      // 弹窗显示状态
      dialogVisible: false,
      // 表单数据（新增/编辑用）
      form: {
        dictId: '',
        dictType: '',
        dictCode: '',
        dictName: '',
        description: '',
        sortOrder: 0,
        isActive: 0
      }
    }
  },
  mounted() {
    this.getTableData()
    this.fetchDictTypes()
  },
  methods: {
    // 获取表格数据
    getTableData() {
      axios.get('/dict/page',{
        params:{
          current:this.current,
          size:this.size,
          dictType:this.searchForm.dictType || undefined,
          dictName:this.searchForm.dictName || undefined
        }
      }).then(response => {
        if (response.data.code = 200){
          this.tableData = response.data.data.records
          this.total = response.data.data.total
        }else {
          this.$message.error(response.data.message || '获取字典列表失败');
        }

      })

    },
    //获取字典类型
    fetchDictTypes() {
      axios.get('/dict/types').then( response =>{
        if (response.data.code === 200) {
          this.dictTypes = response.data.data;
        }else {
           console.error('获取字典类型失败', error);
        }
      })
    },
    // 查询
    handleSearch() {
      this.current = 1
      this.getTableData()
    },
    // 重置查询条件
    resetSearch() {
      this.searchForm.dictType = ''
      this.searchForm.dictName = ''
      this.handleSearch()
    },
    // 分页 - 每页条数改变
    handleSizeChange(val) {
      this.size = val
      this.current = 1
      this.getTableData()
    },
    // 分页 - 当前页改变
    handleCurrentChange(val) {
      this.current = val
      this.getTableData()
    },
    // 多选框改变
    handleSelectionChange(val) {
      this.selectedRows = val
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true
      this.form = {
        dictId: '',
        dictType: '',
        dictCode: '',
        dictName: '',
        description: '',
        sortOrder: 0,
        isActive: 1
      }
    },
    // 编辑
    handleEdit(row) {
      this.dialogVisible = true
      this.form = { ...row }
    },
    // 删除（单个）
    handleDelete(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/dict/delete',{
          params:{
            dictId: row.dictId
          }
        }).then( () =>{
          const index = this.tableData.findIndex(item => item.dictId === row.dictId)
          if (index !== -1) {
            this.tableData.splice(index, 1)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 状态切换处理函数
    handleSwitchChange(dict, newStatus) {
      const action = newStatus === 0 ? '禁用' : '启用';
      const statusText = newStatus === 0 ? '禁用' : '正常';
      this.$confirm(`确定要${action}吗?`, '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        axios.post(`/dict/updateStatus?dictId=${dict.dictId}&status=${dict.isActive}`).then(response => {
          if (response.data.code == 200) {
            this.$message.success(`状态已更新为: ${statusText}`);
          } else {
            dict.isActive = dict.isActive === 1 ? 0 : 1;
            this.$message.error('状态更新失败: ' + response.data.message);
          }
        }).catch(error => {
          dict.isActive = dict.isActive === 1 ? 0 : 1;
          this.$message.error('请求失败: ' + error.message);
        });
      }).catch(() => {
        dict.isActive = dict.isActive === 1 ? 0 : 1;
        this.$message.info('操作已取消');
      });
    },
    // 保存（新增/编辑）
    handleSave() {
      // 简单校验，可根据实际需求完善
      if (!this.form.dictType) {
        this.$message.error('请输入字典类型')
        return
      }
      if (!this.form.dictName) {
        this.$message.error('请输入字典名称')
        return
      }
      // 发送请求
      axios.post('/dict/saveOrUpdate', this.form,)
          .then(response =>{
            if (response.data.code === 200) {
              this.$message.success(this.form.dictId ? '修改成功' : '添加成功');
              this.dialogVisible = false;
              // 刷新列表
              this.handleCurrentChange(this.current);
              this.dialogVisible = false;
            } else {
              this.$message.error(response.data.message || '操作失败，请重试');
            }
          })
    }
  }
}
</script>

<style scoped>
.news-dict-container {
  padding: 20px;
}
.filter-card {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
